package com.kinglone.back.role.controller;

import com.kinglone.back.role.model.Role;
import com.kinglone.back.role.service.RoleService;
import com.kinglone.back.user.model.User;
import com.kinglone.back.user.service.UserService;
import com.kinglone.common.entity.PageBean;
import com.kinglone.common.node.ZTreeNode;
import com.kinglone.common.utils.ResponseUtil;
import com.kinglone.common.utils.ResultMsg;
import com.kinglone.common.utils.StringUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/role")
public class RoleController {

    protected final static Logger logger = LogManager.getLogger(RoleController.class);
    @Autowired
    private RoleService roleService;
    @Autowired
    private UserService userService;

    @RequestMapping("/showRole")
    public String showRole(HttpServletRequest request){
        logger.info("跳转到角色列表");
        return "role/roleList";
    }
    /**
     * 跳转到角色分配
     */
    @RequestMapping(value = "/role_assign/{roleId}")
    public String roleAssign(@PathVariable("roleId") Integer roleId, Model model) {

        model.addAttribute("roleId", roleId);
       // model.addAttribute("roleName", ConstantFactory.me().getSingleRoleName(roleId));
        return  "role/assign";
    }

    @RequestMapping("/roleList")
    public String roleList( String page, String limit,Role role, HttpServletResponse response){
        logger.info("----------------------查询角色列表信息");
        try {
            PageBean pageBean = new PageBean(Integer.parseInt(page), Integer.parseInt(limit));
            JSONObject result = new JSONObject();

            Map<String, Object> map = new HashMap<String, Object>();
            map.put("param",role);
            map.put("start", pageBean.getStart());
            map.put("size", pageBean.getPageSize());

            List<Role> rolelist = roleService.list(map);
            int count = roleService.getTotal(map);
            JSONArray jsonArray = JSONArray.fromObject(rolelist);
            result.put("code",0);
            result.put("msg","");
            result.put("data", jsonArray);
            result.put("count", count);
            System.out.println(result);
            ResponseUtil.write(response, result);
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取角色列表
     */
    @RequestMapping(value = "/roleTreeListByUserId/{userId}")
    @ResponseBody
    public List<ZTreeNode> roleTreeListByUserId(@PathVariable String userId) {
        try {
            User theUser = this.userService.selectById(userId);
            String roleid = theUser.getRoleid();
            if (StringUtil.isEmpty(roleid)) {
                List<ZTreeNode> roleTreeList = this.roleService.roleTreeList();
                return roleTreeList;
            } else {
                String[] strArray = StringUtil.toStrArray(",", roleid);
                List<ZTreeNode> roleTreeListByUserId = this.roleService.roleTreeListByRoleId(strArray);
                return roleTreeListByUserId;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
       return null;
    }

    /**
     * 配置权限
     * @param roleId,ids
     * @return
     */
    @RequestMapping("/setAuthority")
    @ResponseBody
    public ResultMsg setAuthority(@RequestParam("roleId") Integer roleId, @RequestParam("ids") String ids){
        ResultMsg msg = new ResultMsg();
        try {
            msg = roleService.setAuthority(roleId, ids);
        }catch (Exception e){
            e.printStackTrace();
            msg.setMessage("权限配置失败!");
            msg.setSuccess(false);
            return msg;
        }
        return msg;
    }

}
